package com.smart.web.service.impl;

import com.smart.web.entity.Order;
import com.smart.web.entity.OrderItem;
import com.smart.web.mapper.OrderMapper;
import com.smart.web.reqeust.OrderRequestParam;
import com.smart.web.reqeust.ProductRequestParams;
import com.smart.web.service.CartItemService;
import com.smart.web.service.OrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * .............................................
 * When I wrote this, only God and I understood what I was doing
 * Now, God only knows
 * .............................................
 *
 * @ProjectName: spring-boot-demo
 * @Package: com.smart.web.service.impl
 * @ClassName: OrderServiceImpl
 * @Description: 描述
 * @Author: zhangwei
 * @CreateDate: 2021/12/10 17:24
 * @UpdateUser: 更新者
 * @UpdateDate: 2021/12/10 17:24
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class OrderServiceImpl implements OrderService {
    @Resource
    OrderMapper orderMapper;
    @Resource
    CartItemService cartItemService;

    /**
     * 保存订单信息
     * 订单号
     * 收货地址
     * 会员ID
     * 总金额  单间商品价格* 数量
     * 订单详情表
     * 关联订单号
     * 商品信息
     * 删除购物车的购买商品信息
     * 返回 --->
     * <p>
     * 减库存   库存  100   0    销售量   90
     * <p>
     * 支付总结 订单的名称  订单号
     * 选择支付方式
     * ---->  发起支付
     * 支付系统
     *
     * @return
     */
    @Override
    @Transactional
    public int createOrder(OrderRequestParam requestParam) {
        Order order = new Order();
        //设置订单号
        String orderSn = "123456";
        order.setOrderSn(orderSn);
        order.setMemberId(requestParam.getMemberId());
        order.setNote(requestParam.getMsg());
        //设置收货地址的相关信息
        BeanUtils.copyProperties(requestParam.getAddress(), order);
        // 计算总金额
//        加法 add()函数     减法subtract()函数
//        乘法multiply()函数    除法divide()函数
        BigDecimal totalAmount = new BigDecimal("0.00");
        List<ProductRequestParams> products = requestParam.getProducts();
        products.forEach(productRequestParams -> {
//            单价 * 数量
            BigDecimal multiply = productRequestParams.getProductPrice().multiply(new BigDecimal(productRequestParams.getProductQuantity()));
            totalAmount.add(multiply);
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderSn(orderSn);
            // 1. 通过商品ID查询库存信息
            // 库存  >=    productRequestParams.getProductQuantity()
            //  库存- 购买数量
            // 更新库存信息
            BeanUtils.copyProperties(productRequestParams, orderItem);
        });
        orderMapper.insert(order);
        order.setTotalAmount(totalAmount);
        //
        List<Long> ids = products.stream().map(ProductRequestParams::getCartId).collect(Collectors.toList());
//        删除购物车信息
        cartItemService.batchDel(ids);

        return 0;
    }
}
